package com.lemon.cloud.comm.model;

import lombok.Data;

import java.io.Serializable;
import java.util.Objects;

/**
 * @author HuangDS
 */
@Data
public class ResultMsg<T> implements Serializable {
    private Integer code;

    private String msg;

    private T data;

    private Boolean success;

    public static <T> ResultMsg<T> resultSuccess(){
        return new ResultMsg<>(ResultCode.REQUEST_SUCCESS.getCode(),ResultCode.REQUEST_SUCCESS.getMsg(),null);
    }

    public static <T> ResultMsg<T> resultFail(T data){
        return new ResultMsg<>(ResultCode.SERVICE_EXCEPTION.getCode(),null,data);
    }

    public static <T> ResultMsg<T> resultFail(String msg){
        return new ResultMsg<>(ResultCode.SERVICE_EXCEPTION.getCode(),msg,null);
    }

    public static <T>  ResultMsg<T> resultFail(Integer code,String msg){
        return new ResultMsg<>(code,msg,null);
    }

    public static <T>  ResultMsg<T> resultFail(ResultCode resultCode){
        return new ResultMsg<>(resultCode.getCode(),resultCode.getMsg(),null);
    }


    public static boolean isSuccess(ResultMsg<?> resultMsg){
        return Objects.nonNull(resultMsg)&&resultMsg.getCode().equals(ResultCode.REQUEST_SUCCESS.getCode());
    }

    public static <T> ResultMsg<T> resultSuccess(T data){
        return new ResultMsg(ResultCode.REQUEST_SUCCESS.getCode(),ResultCode.REQUEST_SUCCESS.getMsg(),data);
    }

    private ResultMsg(){}

    public ResultMsg(Integer code, String msg, T data){
        this.code=code;
        this.msg=msg;
        this.data=data;
        if (code==ResultCode.REQUEST_SUCCESS.getCode()){
            this.success=true;
        }
    }

    public Boolean isSuccess(){
        if (this.getCode()==ResultCode.REQUEST_SUCCESS.getCode()){
            return true;
        }
        return false;
    }

    public static <T> ResultMsg<T> restResult(T data, int code, String msg) {
        ResultMsg<T> apiResult = new ResultMsg<>();
        apiResult.setCode(code);
        apiResult.setData(data);
        apiResult.setMsg(msg);
        return apiResult;
    }
}
